package com.tudou.geo.util;

import java.util.HashSet;
import java.util.Set;

import org.apache.commons.lang.StringUtils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;

public class Utility {
	
	public static long ip2long(String ip){
		if(!ip.matches("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"))
			return 0;	
		
		String[] array=ip.split("\\.");
		return (Long.parseLong(array[0])<<24)+(Long.parseLong(array[1])<<16)+(Long.parseLong(array[2])<<8)+Long.parseLong(array[3]);
	}
	
	public static String long2ip(long value){
		String result="";
		for(int i=0;i<3;i++){
			result="."+(value%256)+result;
			value=value/256;
		}
		result=(value%(256L<<24))+result;
		return result;
	}
	
	public static Set<String> getPinyin(String chinese){
		
		if(StringUtils.isBlank(chinese)){
			return new HashSet<String>();
		}
		
		HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
		format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		
		try{
			Set<String> result = new HashSet<String>();
			result.add("");
			
			for(char c : chinese.toCharArray()){
				String[] pinyin = PinyinHelper.toHanyuPinyinStringArray(c, format);
				result = joinPinyin(result,pinyin);
				
			}
			
			return result;
		}catch(Exception e){
			e.printStackTrace();
			return new HashSet<String>();
		}
	}
	
	private static Set<String> joinPinyin(Set<String> src1,String[] src2){
		Set<String> result = new HashSet<String>();
		
		for(String j : src1){
			
			for(String t : src2){
				result.add(j + t);
			}
		}
		
		return  result;
	}
}
